import { defineStore } from "pinia";

import { findPagerUserClient } from "@/api/modules/eventManagement";

import { findMySupportITSOPUserPager, findAllClienk } from "@/api/modules/common";

import { findByCode, getCategoryTree } from "@/api/modules/changeManagement";

import { useUserStore } from "./user";

interface TreeNode {
  attr?: Record<string, any>; // attr 是一个可选的对象，键是字符串，值是任意类型
  children?: TreeNode[]; // children 是一个可选的 TreeNode 数组
}

function flattenAttr(nodes: TreeNode[]): TreeNode[] {
  return nodes.map(node => {
    const result: TreeNode = {
      children: node.children ? flattenAttr(node.children) : []
    };

    if (node.attr) {
      // 使用对象解构和展开运算符将 attr 的内容复制到 result 对象中
      // 注意：这里会覆盖 result 对象中可能已存在的同名属性（如果有的话）
      Object.assign(result, node.attr);
    }

    // 由于我们已经明确设置了 children，所以这里不需要再检查 undefined
    return result;
  });
}

interface optionsItem {
  cateList: any;
  orgList: any;
  priorityList: any;
  seriousnessList: any;
  effectRangeList: any;
  statusList: any;
  groupList: TreeNode[];
  userList: any;
}

export const useAllChangeOptions = defineStore({
  id: "change-options",
  state: (): optionsItem => ({
    cateList: [], // 分类列表
    orgList: [], // 所属客户列表
    priorityList: [], // 优先级列表
    seriousnessList: [], // 紧急度列表
    effectRangeList: [], // 影响列表
    statusList: [], // 变更状态列表
    groupList: [], // 指派组列表
    userList: [] // 申请人列表
  }),
  getters: {},
  actions: {
    // 获取请求人列表
    getUserList(companyNo: number) {
      findPagerUserClient({
        "userQueryDto.companyNo": companyNo,
        "userQueryDto.loginName": "",
        Sord: "desc",
        sidx: "userId",
        _search: false,
        page: 1,
        rows: 100
      }).then((res: any) => {
        this.userList = res.data || [];
      });
    },
    async getAllOptions() {
      const userStore = useUserStore();
      // 获取所属客户列表
      await findMySupportITSOPUserPager({
        "itsopUserQueryDTO.loginName": userStore.username,
        sidx: "orgNo",
        sord: "desc",
        page: 1,
        rows: 100
      }).then((res: any) => {
        this.orgList = res.data || [];
      });
      // 获取分类列表
      await getCategoryTree({
        types: "Change",
        parentEventId: 0
      }).then((res: any) => {
        let arr = res.children || [];
        this.cateList = arr.map(item => {
          if (item.attr && item.attr.id) {
            item.attr.id = parseInt(item.attr.id);
          }
          return item.attr;
        });
      });
      // 获取优先级列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "priority"
      }).then((res: any) => {
        let list = res || [];
        this.priorityList = list;
      });
      // 获取紧急度列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "seriousness"
      }).then((res: any) => {
        let list = res || [];
        this.seriousnessList = list;
      });
      // 影响范围列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "effectRange"
      }).then((res: any) => {
        let list = res || [];
        this.effectRangeList = list;
      });
      // 变更状态列表
      await findByCode({
        "dataDictionaryQueryDto.groupCode": "changeStatus"
      }).then((res: any) => {
        let list = res || [];
        this.statusList = list;
      });
      // 指派组
      findAllClienk({
        companyNo: userStore.userInfo.companyNo,
        parentOrgNo: 0,
        _: new Date().getTime()
      }).then((res: any) => {
        this.groupList = flattenAttr(res.children);
      });
    }
  }
});
